import { addRule, removeRule, rule, updateRule } from '@/services/auth/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ColumnsState, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  PageContainer,
  ProTable,
  TableDropdown
} from '@ant-design/pro-components';
import { history } from 'umi';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import { pagedProduct, activeProduct ,deleteProductInfoConfig} from '@/services/product/product_api';
import dayjs from 'dayjs';
import AddProductDrawer from './AddProductDrawer';
import { formatToLocalTime } from '@/utils/time';



const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [apiModalOpen, handleApiModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<ProductInfoVo>();
  const [selectedRowsState, setSelectedRows] = useState<ProductInfoVo[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const makeActive = (id: string, status: string) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'pages.product.confirm.title' }),
      content: intl.formatMessage(
        { id: 'pages.product.confirm.content' },
        { action: status === "1" ? 
            intl.formatMessage({ id: 'pages.product.activate' }) : 
            intl.formatMessage({ id: 'pages.product.deactivate' }) }
      ),
      okText: intl.formatMessage({ id: 'pages.confirm' }),
      cancelText: intl.formatMessage({ id: 'pages.cancel' }),
      onOk: async () => {
        const hide = message.loading(intl.formatMessage({ id: 'pages.processing' }));
        try {
          await activeProduct({ prId: id, prStatus: status });
          hide();
          message.success(intl.formatMessage(
            { id: 'pages.product.status.success' },
            { action: status === "1" ? 
                intl.formatMessage({ id: 'pages.product.activate' }) : 
                intl.formatMessage({ id: 'pages.product.deactivate' }) }
          ));
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          hide();
          message.error(intl.formatMessage({ id: 'request.error.retry' }));
        }
      },
    });
  }

  const deleteProductCnf = async (record: ProductInfoVo) => {
    const hide = message.loading(intl.formatMessage({ id: 'pages.processing' }));
    try {
      const response = await deleteProductInfoConfig(record.prId);
      hide();
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
        return false;
      }
      
      message.success(intl.formatMessage({ id: 'pages.product.delete.success' }));
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      hide();
      message.error(intl.formatMessage({ id: 'request.error.retry' }));
    }
  }

  const columns: ProColumns<ProductInfoVo>[] = [
    {
      title: <FormattedMessage id="pages.product.name" />,
      dataIndex: 'prName',
    },
    {
      title: (
        <FormattedMessage
          id="pages.product.code"
        />
      ),
      dataIndex: 'prCode',
    },
    {
      title: <FormattedMessage id="pages.product.status" defaultMessage="Status" />,
      dataIndex: 'prStatus',
      hideInForm: true,
      valueEnum: {
        1: {
          text: (
            <FormattedMessage id="pages.status.disabled" defaultMessage="disabled" />
          ),
          status: 'Error',
        },
        0: {
          text: (
            <FormattedMessage id="pages.status.enabled" defaultMessage="enabled" />
          ),
          status: 'Success',
        },

      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.product.spName"
        />
      ),
      dataIndex: 'spName',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.createTime"
          defaultMessage="Create Time"
        />
      ),
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTimeRange',
      hideInForm: true,
      search: false,
      // search: {
      //   transform: (value) => ({
      //     startTime: value[0],
      //     endTime: value[1]
      //   })
      // },
      render: (_, record) => {
        return formatToLocalTime(record.createTime);
        // return dayjs(record.createTime).toString();
      }
    },
    {
      title: (
        <FormattedMessage
          id="pages.updateTime"
          defaultMessage="updateTime"
        />
      ),
      dataIndex: 'updateTime',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => {
        return dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss');
      }
    },

    {
      title: <FormattedMessage id="pages.operating" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        // <a
        //   key="api"
        //   onClick={() => {
        //     setCurrentRow(record);
        //     handleApiModalOpen(true);
        //   }}
        // >
        //   <FormattedMessage id="pages.sp.apilist" defaultMessage="API" />
        // </a>,
        <a key="edit" onClick={() => {
          setCurrentRow(record);   
          console.log('edit info:'+JSON.stringify(record));       
          history.push(`/product/${record.prId}`);
          // handleUpdateModalOpen(true); // 打开编辑弹窗
        }}>
          <FormattedMessage
            id="pages.edit"
            defaultMessage="Edit"
          />
        </a>,
        <a
          key="config"
          onClick={() => {
            makeActive(record.prId, record.prStatus);
            setCurrentRow(record);
          }}
        >
          {record.prStatus == '1' ? (
            <FormattedMessage id="pages.status.enabled" defaultMessage="enabled" />
          ) : (
            <FormattedMessage id="pages.status.disabled" defaultMessage="disabled" />
          )}
        </a>,
        <TableDropdown
          key="actionGroup"
          onSelect={(key) => {
            if (key === "deleteProduct") {
              // 手动触发重置密码逻辑
              deleteProductCnf(record);
               
            }
            // 可以根据需要扩展其他菜单项的逻辑
          }}
          menus={[
            // { key: 'copy', name: '复制' },
            // { key: 'delete', name: '删除' },
            {
              key: "deleteProduct",
              name: ( <FormattedMessage
                    id="pages.delete"
                    defaultMessage="Delete"
                  />)
                
            }, // 新增重置密码菜单项
          ]}
          />
      ],
    },
  ];
  const [columnsStateMap, setColumnsStateMap] = useState<
    Record<string, ColumnsState>
  >({
    updateTime: {
      show: false,
    },
  });
  return (
     <PageContainer title={false}>
      <ProTable<ProductInfoVo, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.product.list',
          defaultMessage: 'Products',
        })}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [

          <Button
            type="primary"
            key="primary"
            onClick={() => {
               history.push(`/product/new`);
              // handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.product.new" defaultMessage="New" />
          </Button>

        ]}
        request={pagedProduct}
        columns={columns}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}


      />

      <AddProductDrawer visible={createModalOpen} 
      onClose={() => {
        handleModalOpen(false)
      }}
        onSuccess={()=> {
          handleModalOpen(false)
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }} />
      

    </PageContainer>
  );
};

export default TableList;
